import React from 'react';
import {
    Tools,
    Bubble,
    Modal,
} from "weaver-mobile";
import loadjs from 'loadjs';
import * as mobx from "mobx";
import {
  checkWeakPass
} from "./PASSUtil.js";
const alert = Modal.alert;
const getLabel = Tools.getLabel;
const jQuery = window.jQuery;
const toJS = mobx.toJS;
let remindNum = 0;

const getLoginForm = (params) => {
    let { langid, callback,queryParams,fromDynamic } = params;
    window.currLanguageId = langid;
    let loginid = params.loginid || '';
    if (loginid == '') {
        loginid = jQuery('#loginid').val();
    }

    let loginFormItems = [];
    let loginFormHiddenItems = [];
    let loginSetting = {};
    let qrCode = {};
    let hasMultiLang = false;

    loginFormItems = [
        { label: '账号', atype: 'account', id: 'loginid', name: 'loginid', type: 'text' },
        { label: '密码', atype: 'password', id: 'userpassword', name: 'userpassword', type: 'password' },
    ];
    
    queryParams = queryParams && toJS(queryParams);
    if((queryParams && queryParams.appid && queryParams.service && queryParams.message)){
       if(remindNum==0){
			remindNum = remindNum+1;
			Tools.callApi({
				url: '/api/integration/common1/getMessageByCode',
				method:'POST',
				params : {code:queryParams.message,language:langid}
			}).then((rs)=>{
				Bubble.error(rs.message, 3);
			}).catch(err=>{
				if(console) console.log(err) ;
			})
		}
    }

    Tools.callApi({
        url: '/api/hrm/login/getLoginForm', method: 'POST', params: { loginid, langid,fromDynamic:fromDynamic }
    }).then((result) => {
        loginFormItems = result.formItems;
        loginSetting = result.loginSetting;
        qrCode = result.qrcode;
        hasMultiLang = loginSetting.hasMultiLang;
        loginFormHiddenItems = [
            { html: '<input type="hidden" id="messages" name="messages" value="">' }
        ];

        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting, qrCode });
    }).catch((err) => {
        Bubble.error(err);
        if (callback && typeof callback == 'function') callback({ hasMultiLang, loginFormItems, loginFormHiddenItems, loginSetting, qrCode });
    });
};

const login = (params) => {
    const { openRSA } = params.loginSetting;
    if (openRSA && openRSA == '1') {//启用RSA加密
        window.__RSAEcrypt__.refreshRsaCode(function () {
            loginSync(params);
        });
    } else {
        loginSync(params);
    }
};

const loginSync = (params) => {
    const { userUsbType, hasMultiLang, hasValidateCode, validateCodeKey, numValidateWrong, validateType, showDynamicPwd, openRSA } = params.loginSetting;
    let { langid, success, failure, logintype, languageIdentify,queryParams,fromDynamic} = params;
    let langid4em = '';
    for(var i=0;i<languageIdentify.length ;i++){
        if(languageIdentify[i][langid] && languageIdentify[i][langid]!=''){
            langid4em = languageIdentify[i][langid]
        }
    }
    const loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    const dynamicPassword = jQuery('#dynamicPassword').val();
    let loginidRsa = loginid ;
    let userpasswordRsa = userpassword;
    if(openRSA && openRSA=='1'){//启用RSA加密
        userpasswordRsa = window.__RSAEcrypt__.rsa_data_encrypt(userpassword);
        loginidRsa = window.__RSAEcrypt__.rsa_data_encrypt(loginid) ;
    }

    const tokenAuthKey = jQuery('#tokenAuthKey') ? jQuery('#tokenAuthKey').val() : '';
    const validatecode = jQuery('#validatecode') ? jQuery('#validatecode').val() : '';
    const messages = jQuery('#messages') ? jQuery('#messages').val() : '';
    Bubble.hide();

    if(jQuery('#userpassword') && jQuery('#userpassword').length>0){
        if (loginid == '' || userpassword == '') {
            Bubble.error(getLabel('386478',"请输入用户名、密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    if(jQuery('#dynamicPassword') && jQuery('#dynamicPassword').length>0){
        if(dynamicPassword==''){
            Bubble.error(getLabel('20289',"请输入动态密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    if (hasValidateCode && hasValidateCode == '1' && validatecode == '') {
        Bubble.error(getLabel('84270', "请输入验证码"), 3);
        if (failure && typeof failure == 'function') failure();
        return;
    }

    if (userUsbType == '3') {
        if (tokenAuthKey == '') {
            Bubble.warning(getLabel('84271', "请输入动态令牌口令"));
            if (failure && typeof failure == 'function') failure();
            return;
        } else if (!isdigit(tokenAuthKey) || tokenAuthKey.length != 6) {
            Bubble.warning(getLabel('386435', "动态令牌口令必须为6位数字！"));
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    queryParams = toJS(queryParams);
    if(queryParams && queryParams.appid && queryParams.service){
        queryParams.loginid=loginid;
        queryParams.userpassword=userpasswordRsa;
        queryParams.isRememberAccount = params.isRememberAccount ? '1':'0' ;
        queryParams.isRememberPassword = params.isRememberPassword ? '1':'0' ;
        queryParams.validatecode = validatecode;
        queryParams.validateCodeKey = validateCodeKey;
        queryParams.languid=langid;
        let tmps = [];
        jQuery("body").append("<form name='ssoForm'></form>");
        let form = jQuery("form[name='ssoForm']")
        form.attr("action", '/login/VerifyLoginWeaversso.jsp');
        form.attr("method", "post");
        form.attr("style", "display:none");
        for (let key in queryParams) {
            form.append("<input type='text' name='" + key + "' value = '" + queryParams[key] + "'></input>");
        }
        //跳转到sso
        form.submit();
        return;
    }




    Tools.callApi({
        url: '/api/hrm/login/checkLogin',
        method: 'POST',
        params: {
            islanguid: langid,
            loginid: loginidRsa,
            userpassword: userpasswordRsa,
            dynamicPassword:dynamicPassword,
            tokenAuthKey: tokenAuthKey,
            validatecode: validatecode,
            validateCodeKey: validateCodeKey,
            logintype: logintype,
			fromDynamic:fromDynamic,
            messages: messages
        }
    }).then((result) => {
        if ('access_token' in result && typeof result.access_token === 'string' && result.access_token !== '') {
            localStorage.setItem('access_token', result.access_token);
        } else {
            localStorage.access_token && localStorage.removeItem('access_token');
        }

        if (result.user_token && result.user_token != '') {
            userpassword = result.user_token;
        }

        if (result.loginstatus == 'true') {
            const onOk = () => {
                showDialog("/spa/hrm/static4mobile/index.html#/changePassword", true);
            };
            const onCancel = () => {
                if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
            };
            const onSuccess = () => {
                ssoLogin({success,loginid, userpassword, langid4em,result});
            }

            const pass = jQuery('#userpassword').val();
            if (success && typeof success == 'function') {
                Bubble.hide();
                if (logintype == 2) {
                    //success(loginid, userpassword, result);
                    // ssoLogin({success,loginid, userpassword, langid4em,result});
                    checkWeakPass(pass,onOk,onCancel,onSuccess);
                } else {
                    Tools.callApi({
                        url: '/api/hrm/login/remindLogin',
                        method: 'POST',
                        params: { logintype: logintype }
                    }).then((result) => {
                        if (result.status == '1') {
                            if (result.isUpPswd == 'true') {
                                if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                alert(getLabel(15172, '系统提示'), getLabel('81626', "首次登录需修改密码！"), [
                                    {
                                        text: getLabel(826, '确定'), onPress: () => {
                                            if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                            showDialog("/spa/hrm/static4mobile/index.html#/changePassword?optype=2",true);
                                            return;
                                        }
                                    },
                                    {
                                        text: getLabel(201, '取消'), onPress: () => {
                                            if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                            Tools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                            return;
                                        }
                                    },
                                ]);
                            } else {
                                if (result.passwdReminder == '1') {
                                    if (result.canpass == '1') {
                                        if (result.canremind == '1') {
                                            const content = getLabel('386479', "您的密码还有{params}天过期,是否现在修改?").replace('{params}', result.passwdelse);
                                            alert(getLabel(15172, '系统提示'), content, [
                                                {
                                                    text: getLabel(826, '确定'), onPress: () => {
                                                        if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                                        showDialog("/spa/hrm/static4mobile/index.html#/changePassword",true);
                                                        return;
                                                    }
                                                },
                                                {
                                                    text: getLabel(201, '取消'), onPress: () => {
                                                        //success(loginid, userpassword, result);
                                                        // ssoLogin({success,loginid, userpassword, langid4em,result});
                                                        checkWeakPass(pass,onOk,onCancel,onSuccess);
                                                    }
                                                },
                                            ]);
                                        } else {
                                            //success(loginid, userpassword, result);
                                            // ssoLogin({success,loginid, userpassword, langid4em, result});
                                            checkWeakPass(pass,onOk,onCancel,onSuccess);
                                        }
                                    } else {
                                        alert(getLabel(15172, '系统提示'), getLabel('386480', "您的密码已经过期,请立即修改！"), [
                                            {
                                                text: getLabel(826, '确定'), onPress: () => {
                                                    if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                                    showDialog("/spa/hrm/static4mobile/index.html#/changePassword?optype=1",true);
                                                    return;
                                                }
                                            },
                                            {
                                                text: getLabel(201, '取消'), onPress: () => {
                                                    if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
                                                    Tools.callApi('/api/hrm/login/checkLogout', 'POST', {}).then((result) => { });
                                                    return;
                                                }
                                            },
                                        ]);
                                    }
                                } else {
                                    //success(loginid, userpassword, result);
                                    // ssoLogin({success,loginid, userpassword, langid4em, result});
                                    checkWeakPass(pass,onOk,onCancel,onSuccess);
                                }
                            }
                        }
                    });
                }
            }
        } else {
            if (failure && typeof failure == 'function') failure({ reflashValidateCode: true });
            Bubble.hide();
            let errorMsg = result.msg || getLabel('386481', "登录失败");
            let errorUrl = '';
            let errorText = '';

            if (result.msgcode == '120') {
                errorText =","+ getLabel('507855', "请去PC端")+getLabel('388043', "绑定令牌");
            } else if (result.msgcode == '122') {
                errorText =","+ getLabel('507855', "请去PC端")+getLabel('84269', "同步令牌");
            } else if (result.msgcode == '19') {
                errorText =","+ getLabel('507855', "请去PC端")+getLabel('18640', "提交License");
                return;
            }

            // 返回错误信息提示
            Bubble.error((
                <span>
                    {errorMsg + errorText}
                </span>
            ), 5);
        }
    });
};

const getDynamicPassword = (params) => {
    let { langid, success, failure} = params;
    const {openRSA} = params.loginSetting;
    const loginid = jQuery('#loginid').val();
    const userpassword = jQuery('#userpassword').val();
    const dynamicPassword = jQuery('#dynamicPassword').val();

    Bubble.hide();
    if(jQuery('#userpassword') && jQuery('#userpassword').length>0){
        if (loginid == '' || userpassword == '') {
            Bubble.error(getLabel('386478',"请输入用户名、密码"), 3);
            if (failure && typeof failure == 'function') failure();
            return;
        }
    }

    if(openRSA && openRSA=='1'){//启用RSA加密
        window.__RSAEcrypt__.refreshRsaCode(function(){
            getDynamicPasswordSync(params);
        });
    }else{
        getDynamicPasswordSync(params);
    }
};

const getDynamicPasswordSync = (params) => {
    let {langid, success, failure} = params;
    const {openRSA} = params.loginSetting;
    let loginid = jQuery('#loginid').val();
    let userpassword = jQuery('#userpassword').val();
    let loginidRsa = loginid;
    let userpasswordRsa = userpassword;
    if(openRSA && openRSA=='1'){//启用RSA加密
        loginidRsa = window.__RSAEcrypt__.rsa_data_encrypt(loginid) ;
        userpasswordRsa = window.__RSAEcrypt__.rsa_data_encrypt(userpassword);
    }

    Tools.callApi({
        url: '/api/hrm/login/getDynamicPassword',
        method: 'POST',
        params: {langid: langid,
                loginid: loginidRsa,
                userpassword: userpasswordRsa,}
    }).then((result) => {
        if (result.status == '1') {
            if (success && typeof success == 'function') {
                success(result);
            }
        } else {
            Bubble.hide();
            let errorMsg = result.message;
            // 返回错误信息提示
            Bubble.error((
                <span>
                    {errorMsg}
                </span>
            ), 5);
        }
    });
};

const ssoLogin = (params) => {
    const { success,failure,loginid, userpassword, langid4em, result } = params;
    if (window.em && window.em.checkJsApi("ssoLogin")) {
        Tools.callApi({
            url: '/api/ec/dev/app/getSSOCode',
            method: 'get',
            params: {}
        }).then((ssoRes) => {
            window.em.ssoLogin({
                ssokey: ssoRes.keycode,
                lang_type: langid4em,
                account: '',
                into: 0,
                success: function (data) {
                    if (data.errCode && data.errCode != 0) {
                        Bubble.error(data.errMsg, 5);
                    }
                    success(loginid, userpassword, result);
                },
                fail: function (err) {
                    Bubble.error(err.errMsg, 5);
                    // console.log(err);
                    if (failure && typeof failure == 'function') failure({reflashValidateCode:true});
                },
                complete: function (res) {
                    //console.log(res);
                }
            });
        });
    }else{
        success(loginid, userpassword, result);
    }
};

const showDialog = (url,flag) => {
    if(checkIsEmPC() && flag){
        showDialogIframe(url);
        return ;
    }else{
        if (window.em && window.em.checkJsApi('openLink')) {
            let emobile_ec_id = window.localStorage.emobile_ec_id;
            emobile_ec_id='';//不需要登录em
            window.em.openLink({
                sysId: emobile_ec_id,
                url: url,
                openType: 2
            });
        } else {
            window.open(url);
        }
    }
};

const checkIsEmPC = ()=>{
    const ua = window.navigator.userAgent;
    if ((ua && ua.indexOf('Electron') > -1) || (ua && ua.indexOf('nw/0.14.7') > -1)) {  
        return true;
    }
    return false ;
}

const showDialogIframe = (url) =>{
    jQuery('#first_password_iframe').remove();
    var frameView = document.createElement("div");
    frameView.style.position = "fixed";
    frameView.style.width = "100%";
    frameView.style.height = "100%";
    frameView.style.top = 0;
    frameView.style.left = 0;
    frameView.style.zIndex = 998;
    frameView.innerHTML = '<iframe style="border:none;height:100%;width:100%" src="' + url + '"></iframe>';
    document.body.appendChild(frameView);
}

const isdigit = (s) => {
    var r, re;
    re = /\d*/i; //\d表示数字,*表示匹配多个数字
    r = s.match(re);
    return (r == s) ? true : false;
}

// 提供登录相关的全局方法
window.doLoginAction = (actionName, params) => {
    const { langid } = params; 
    if (actionName == 'getLoginForm') {
        Tools.getLocaleLabelByLang('common,hrm',langid).then(() => {
            getLoginForm(params);
        });
    } else if (actionName == 'login') {
        //异步加载ras文件
        loadjs.isDefined('rsa') ? loadjs.ready('rsa', () => {
            login(params)
        }) : loadjs(["/js/rsa/jsencrypt.js", "/js/rsa/rsa.js"], 'rsa', {
            async: false,
            success: () => {
                login(params)
            }
        });
    } else if (actionName == 'getDynamicPassword') {
        //异步加载ras文件
        loadjs.isDefined('rsa') ? loadjs.ready('rsa', () => {
            getDynamicPassword(params);
        }) : loadjs(["/js/rsa/jsencrypt.js", "/js/rsa/rsa.js"], 'rsa', {
            async: false,
            success: () => {
                getDynamicPassword(params);
            }
        });
    } else if (actionName == 'forgetPassword') {
        showDialog("/spa/hrm/static4mobile/index.html#/forgetPassword?languageId="+langid);
    }
};